import React, { useState, useEffect } from 'react';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import { motion } from 'framer-motion';
import TaskForm from './components/TaskForm';
import TaskItem from './components/TaskItem';
import TagFilter from './components/TagFilter';
import ParticleBackground from './components/ParticleBackground';

function App() {
  // 状态管理
  const [tasks, setTasks] = useState([]);
  const [filter, setFilter] = useState('all'); // all, active, completed
  const [darkMode, setDarkMode] = useState(false);
  const [newTaskAnimation, setNewTaskAnimation] = useState(false);
  const [taskToEdit, setTaskToEdit] = useState(null);

  // 从localStorage加载数据
  useEffect(() => {
    const savedTasks = localStorage.getItem('tasks');
    const savedDarkMode = localStorage.getItem('darkMode') === 'true';
    
    if (savedTasks) {
      setTasks(JSON.parse(savedTasks));
    }
    
    setDarkMode(savedDarkMode);
  }, []);

  // 保存数据到localStorage
  useEffect(() => {
    localStorage.setItem('tasks', JSON.stringify(tasks));
  }, [tasks]);

  useEffect(() => {
    localStorage.setItem('darkMode', darkMode);
    if (darkMode) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
  }, [darkMode]);

  // 添加新任务
  const addTask = (task) => {
    setNewTaskAnimation(true);
    setTasks([...tasks, { ...task, id: Date.now(), completed: false }]);
    // 重置动画状态
    setTimeout(() => setNewTaskAnimation(false), 750);
  };

  // 更新任务
  const updateTask = (updatedTask) => {
    setTasks(tasks.map(task => task.id === updatedTask.id ? updatedTask : task));
  };

  // 删除任务
  const deleteTask = (id) => {
    setTasks(tasks.filter(task => task.id !== id));
  };

  // 切换任务完成状态
  const toggleTaskCompletion = (id) => {
    setTasks(tasks.map(task => 
      task.id === id ? { ...task, completed: !task.completed } : task
    ));
  };

  // 拖拽排序功能
  const moveTask = (fromIndex, toIndex) => {
    const newTasks = [...tasks];
    const [movedTask] = newTasks.splice(fromIndex, 1);
    newTasks.splice(toIndex, 0, movedTask);
    setTasks(newTasks);
  };

  // 获取所有唯一标签
  const allTags = [...new Set(tasks.flatMap(task => task.tags || []))];
  
  // 标签过滤状态
  const [selectedTag, setSelectedTag] = useState('all');
  
  // 过滤任务
  const filteredTasks = tasks.filter(task => {
    // 状态过滤
    if (filter === 'active' && task.completed) return false;
    if (filter === 'completed' && !task.completed) return false;
    
    // 标签过滤
    if (selectedTag !== 'all' && (!task.tags || !task.tags.includes(selectedTag))) return false;
    
    return true;
  });

  return (
    <DndProvider backend={HTML5Backend}>
      <div className={`min-h-screen ${darkMode ? 'dark bg-gray-900 text-white' : 'bg-gray-100 text-gray-900'} transition-colors duration-200`}>
        <div className="container mx-auto px-4 py-8 max-w-4xl relative">
            <div className="flex justify-between items-center mb-8">
              <h1 className="text-3xl font-bold">待办事项清单</h1>
              <motion.button 
                onClick={() => setDarkMode(!darkMode)}
                className="p-2 rounded-full bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors transform hover:scale-110 icon-scale-hover"
                whileHover={{ scale: 1.1 }}
                whileTap={{ scale: 0.9 }}
                animate={{ 
                  backgroundColor: darkMode ? '#374151' : '#E5E7EB',
                  color: darkMode ? '#F3F4F6' : '#1F2937'
                }}
                transition={{ duration: 0.5 }}
              >
                {darkMode ? '☀️' : '🌙'}
              </motion.button>
            </div>
            
            <TaskForm onAddTask={addTask} />
        
        <div className="mb-6 flex space-x-2 transition-all duration-300">
          <button 
            onClick={() => {
              setFilter('all');
              setSelectedTag('all');
            }}
            className={`px-4 py-2 rounded-lg transition-all duration-300 transform hover:scale-105 icon-scale-hover ${filter === 'all' && selectedTag === 'all' ? 'bg-blue-500 text-white transform scale-105 shadow-md' : 'bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600'}`}
          >
            全部
          </button>
          <button 
            onClick={() => {
              setFilter('active');
              setSelectedTag('all');
            }}
            className={`px-4 py-2 rounded-lg transition-all duration-300 transform hover:scale-105 icon-scale-hover ${filter === 'active' && selectedTag === 'all' ? 'bg-blue-500 text-white transform scale-105 shadow-md' : 'bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600'}`}
          >
            未完成
          </button>
          <button 
            onClick={() => {
              setFilter('completed');
              setSelectedTag('all');
            }}
            className={`px-4 py-2 rounded-lg transition-all duration-300 transform hover:scale-105 icon-scale-hover ${filter === 'completed' && selectedTag === 'all' ? 'bg-blue-500 text-white transform scale-105 shadow-md' : 'bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600'}`}
          >
            已完成
          </button>
        </div>
        
        {allTags.length > 0 && (
          <TagFilter 
            tags={allTags}
            selectedTag={selectedTag}
            onTagChange={setSelectedTag}
          />
        )}
          
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg overflow-hidden relative">
            {filteredTasks.length === 0 ? (
            <div className="text-center py-12 relative overflow-hidden">
              <ParticleBackground />
              <div className="relative z-10 particle-container">
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5 }}
                >
                  <div className="text-6xl mb-4">📝</div>
                  <h3 className="text-xl font-semibold mb-2">暂无任务</h3>
                  <p className="text-gray-500">点击上方添加按钮创建新任务</p>
                </motion.div>
              </div>
            </div>
          ) : (
          <ul className="space-y-2 transition-all duration-300">
            <TransitionGroup>
              {filteredTasks.map(task => (
                <CSSTransition
                  key={task.id}
                  timeout={{ enter: 500, exit: 300 }}
                  classNames="task-item"
                >
                  <TaskItem
                    task={task}
                    onToggle={toggleTaskCompletion}
                    onDelete={deleteTask}
                    onEdit={setTaskToEdit}
                    onDragEnd={moveTask}
                  />
                </CSSTransition>
              ))}
            </TransitionGroup>
          </ul>
        )}
          </div>
        </div>
      </div>
    </DndProvider>
  );
}

export default App;
